package com.zhenghaijin.controller;

import com.zhenghaijin.dto.UserDTO;
import com.zhenghaijin.model.User;
import com.zhenghaijin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody UserDTO userDTO) {
        try {
            System.out.println("请求已到达 register 方法，用户名：" + userDTO.getUsername());
            User registeredUser = userService.register(userDTO);
            return ResponseEntity.ok(Map.of(
                "message", "用户注册成功：User registered successfully",
                "userId", registeredUser.getId(),
                "username", registeredUser.getUsername()
            ));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "error", "注册失败：Registration failed",
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "注册错误：Registration error",
                "message", "未知错误：An unexpected error occurred"
            ));
        }
    }



    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody UserDTO userDTO) {
        String token = userService.login(userDTO);
        return ResponseEntity.ok(token);
    }

}
